﻿<template>
  <el-dialog v-drag :title = 'dialogSelectTitle' :visible.sync = 'dialogSelectVisible' width = '65%' :before-close = "handleClose"
  :close-on-click-modal = 'false'>
    <div class = "page_secondMainContent clear">
      <!-- 左侧表的树状列表 -->
      <div class = "page_leftContent">
        <div class = "page_leftSearchContent clear">
          <div class = "page_leftSearchInput" style='margin:0'>
            <el-input  placeholder = "输入表名称" v-model = "filterText" prefix-icon = "el-icon-search"></el-input>
          </div>
        </div>
        <div class = 'main_tree'>
          <el-tree :data = 'treeData' node-key = 'treeId' :check-on-click-node = "true" :check-strictly = 'true' accordion @node-click = "handleNodeClick"
          :filter-node-method = "filterNode" :indent = 10 :props = "defaultProps" ref = 'myTree' show-checkbox @check-change = 'handleCheckChange' :default-expanded-keys = 'defaultExpanded' :default-checked-keys = 'defaultChecked'>
            <span slot-scope='{node, data}' class='page_secondLevel'>
              <span v-if = '!data.hadOperation'>{{node.label}}</span>
              <span v-if = "data.hadOperation" class = "page_treeLabel" style = 'margin-right:0'>{{data.metadesc}}({{data.metaname}})</span>
            </span>
          </el-tree>
        </div>
      </div>
      <!-- 右侧内容区域 -->
      <div class = "page_rightContent">
        <div class = 'page_tableContent'>
          <el-table :data = 'tableData' style = 'width:100%' border stripe height = '400'>
            <el-table-column align = 'center' label = '字段名称'>
              <template slot-scope = 'scope'>
                <span>{{scope.row.column_name}}</span>
              </template>
            </el-table-column>
            <el-table-column align = 'center' label = '字段描述'>
              <template slot-scope = 'scope'>
                <span>{{scope.row.column_desc}}</span>
              </template>
            </el-table-column>
            <el-table-column align = 'center' label = '过滤条件'>
              <template slot-scope = 'scope'>
                <el-row>
                  <el-col :span='6'>
                    <el-select v-model = "scope.row.filerRule">
                      <el-option label = '=' value = 'eq'></el-option>
                      <el-option label = '!=' value = 'neq'></el-option>
                      <el-option label = '>=' value = 'gte'></el-option>
                      <el-option label = '<' value = 'lt'></el-option>
                      <el-option label = '<=' value = 'lte'></el-option>
                      <el-option label = ':' value = 'like'></el-option>
                      <el-option label = '$tree_in' value = '$tree_in'></el-option>
                    </el-select>
                  </el-col>
                  <el-col :span = '16' :offset = '2'>
                    <el-input v-model = 'scope.row.filerTextRule'></el-input>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column label = '关联字段' align = 'center'>
              <template slot-scope = 'scope'>
                <el-radio :label = 'scope.row.column_name' v-model = 'refColumn' @click.native.prevent = "clickItemColumn(scope.row.column_name)"></el-radio>
              </template>
            </el-table-column>
            <el-table-column label = '关联展示字段(展示时)' align = 'center'>
              <template slot-scope = 'scope'>
                <el-radio :label = 'scope.row.column_name' v-model = 'refText' @click.native.prevent = "clickItemText(scope.row.column_name)"></el-radio>
              </template>
            </el-table-column>
            <el-table-column label = '关联显示字段(选择时)' align = 'center'>
              <template slot-scope = 'scope'>
                <el-checkbox :label = 'scope.row.column_name' v-model = 'refShowColumn'></el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <span slot = "footer">
      <el-button type = 'info' @click = "$emit('giveUp')">取 消</el-button>
      <el-button type = "primary" @click = 'handleSubmit'>确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: ['refInfo', 'showDialog', 'currentTable', 'refRow'],
  data () {
    return {
      dialogSelectVisible: false,
      dialogSelectTitle: '选择关联信息',
      refData: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'metadesc'
      },
      defaultExpanded: ['C000'],
      defaultChecked: [],
      filterText: '',
      // 右侧表格的数据
      tableData: [],
      checkedTable: '',
      checkedTableInfo: '',
      refColumn: '',
      refText: '',
      refShowColumn: [],
      refWhere: {}
    }
  },
  methods: {
    // 将数据转换为树状结构
    arrayToTree () {
      let parentArray = this.getParentNode()
      this.treeData = []
      if (parentArray.length) {
        parentArray.forEach(parentVal => {
          const childrenArray = []
          this.refData.forEach(sonVal => {
            // 放开对自己过滤
            // if (this.currentTable !== sonVal.uid) {
            //   sonVal.treeId = sonVal.uid
            //   sonVal.hadOperation = true
            //   sonVal.metaname = sonVal.name
            //   sonVal.metadesc = sonVal.desc
            //   if (parentVal.category_no === sonVal.category_no) {
            //     childrenArray.push(sonVal)
            //   }
            // }
            sonVal.treeId = sonVal.uid
            sonVal.hadOperation = true
            sonVal.metaname = sonVal.name
            sonVal.metadesc = sonVal.desc
            if (parentVal.category_no === sonVal.category_no) {
              childrenArray.push(sonVal)
            }
          })
          const objTem = {
            treeId: parentVal.treeId,
            metaname: parentVal.metaname,
            metadesc: parentVal.metaname,
            category_name: parentVal.category_name,
            category_no: parentVal.category_no,
            disabled: true,
            hadOperation: false,
            children: childrenArray
          }
          this.treeData.push(objTem)
        })
      }
    },
    // 获取树状结构的父节点
    getParentNode () {
      let parentArray = []
      if (this.refData.length) {
        this.refData.forEach(val => {
          if (this.currentTable !== val.uid) {
            if (parentArray.length) {
              let hadParent = true
              parentArray.forEach(pVal => {
                if (val.category_no === pVal.category_no) {
                  hadParent = false
                }
              })
              if (hadParent) {
                let objTem = {
                  treeId: val.category_no,
                  metaname: val.category_name,
                  category_name: val.category_name,
                  category_no: val.category_no,
                  disabled: true
                }
                parentArray.push(objTem)
              }
            } else {
              let objTem = {
                treeId: val.category_no,
                metaname: val.category_name,
                category_name: val.category_name,
                category_no: val.category_no,
                disabled: true
              }
              parentArray.push(objTem)
            }
          }
        })
      }
      return parentArray
    },
    // 获取选中的表
    getCheckedTable () {
      if (this.checkedTableInfo !== '{}' && this.checkedTableInfo) {
        let checked = JSON.parse(this.checkedTableInfo)
        let tableName = checked.$ref_table
        this.refColumn = checked.$ref_key_column
        this.refText = checked.$text
        this.refShowColumn = checked.$show
        this.refWhere = checked.$where
        this.refData.forEach(val => {
          if (val.name === tableName) {
            this.showTableInfo(val)
          }
        })
      } else {
        if (this.refData.length) {
          this.refColumn = ''
          this.refText = ''
          this.refShowColumn = []
          // 剔除本表
          let newArray = this.refData.filter(val => {
            return val.uid !== this.currentTable
          })
          if (newArray.length) {
            this.showTableInfo(newArray[0])
          }
        } else {
          this.tableData = []
        }
      }
    },
    // 展示表的内容
    showTableInfo (data) {
      this.checkedTable = data
      this.tableData = data.columns
      if (this.tableData.length) {
        this.tableData.forEach((val, index) => {
          this.$set(this.tableData[index], 'filerRule', 'eq')
          this.$set(this.tableData[index], 'filerTextRule', '')
        })
      }
      // 如果有过滤条件需要展示
      if (this.refWhere !== '{}') {
        for (let valName in this.refWhere) {
          this.tableData.forEach((dataVal, dataIndex) => {
            if (valName === dataVal.column_name) {
              for (let filterVal in this.refWhere[valName]) {
                this.$set(this.tableData[dataIndex], 'filerRule', filterVal)
                this.$set(this.tableData[dataIndex], 'filerTextRule', this.refWhere[valName][filterVal])
              }
            }
          })
        }
      }
      // 设置树状结构选中的信息
      this.defaultChecked = [data.uid]
      this.defaultExpanded = [data.category_no]
    },
    // 点击树状结构的表时
    handleNodeClick (data, node, self) {
      if (data.hadOperation) {
        // 当点击的不是已经选中的选框时
        if (this.checkedTable !== data) {
          this.checkedTable = data
          this.refColumn = ''
          this.refText = ''
          this.refShowColumn = []
          this.refWhere = {}
          this.$refs.myTree.setCheckedNodes([data])
          this.showTableInfo(data)
        }
      }
    },
    // 树节点的检索
    filterNode (value, data) {
      if (!value) return true
      return data.metadesc.indexOf(value) !== -1 || data.metaname.indexOf(value) !== -1
    },
    // el-tree只能单选
    handleCheckChange (data, node, self) {
      // 点击未选中的复选框
      if (node) {
        this.checkedTable = data
        this.$refs.myTree.setCheckedNodes([data])
      } else {
        // 点击已选中的复选框
        this.$refs.myTree.setCheckedNodes([this.checkedTable])
      }
    },
    // 点击上部的X关闭弹窗时
    handleClose () {
      this.$emit('giveUp')
    },
    // el-radious再次点击取消
    clickItemColumn (e) {
      this.refColumn === e ? this.refColumn = '' : this.refColumn = e
    },
    clickItemText (e) {
      this.refText === e ? this.refText = '' : this.refText = e
    },
    // 点击确定按钮时
    handleSubmit () {
      let refInfo = {}
      let filterInfo = {}
      if (this.refShowColumn.length) {
        // 先判断是否有过滤条件
        this.tableData.forEach(val => {
          if (val.filerTextRule) {
            let objExam = {}
            objExam[val.filerRule] = val.filerTextRule
            filterInfo[val.column_name] = objExam
          }
        })
      }
      refInfo = {
        $ref_table: this.checkedTable.name,
        $ref_key_column: this.refColumn,
        $text: this.refText,
        $show: this.refShowColumn,
        $where: filterInfo
      }
      this.$emit('sureSelectRef', JSON.stringify(refInfo))
    }
  },
  watch: {
    showDialog: {
      handler: function (val, oldVal) {
        this.dialogSelectVisible = val
        if (val) {
          // 是否已经有关联信息
          this.checkedTableInfo = this.refRow
          this.refData = this.refInfo
          // 将表的结构转为树状结构
          this.arrayToTree()
          // 设置默认选中的样式
          this.getCheckedTable()
        }
      },
      deep: true
    },
    filterText (val) {
      this.$refs.myTree.filter(val)
    }
  }
}
</script>

<style lang = "scss" scoped>
.main_tree{
  max-height: 500px;
}
.self_selectRef {
  .page_rightContent {
    background: transparent;
  }
}
@media (max-height:768px) {
  .main_tree {
    max-height: 350px;
  }
}
</style>
